<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card class="box-card">
      <el-row>
        <el-col :span="8">
          <el-button type="primary" @click="showaddCate"
            >添加分类</el-button
          ></el-col
        >
      </el-row>
      <!-- 表格 -->
      <tree-table
        class="table"
        :data="catelist"
        :columns="columns"
        :expand-type="false"
        :selection-type="false"
        border
        show-index
        index-text="#"
        :show-row-hover="false"
      >
        <!-- 是否有效 -->
        <template slot="isok" slot-scope="scope">
          <i
            style="color:lightgreen"
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
          ></i>
          <i class="el-icon-error" v-else></i>
        </template>
        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag
            type="success"
            size="mini"
            v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag type="warning" size="mini" v-else>三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="opt" slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="edit(scope.row.cat_id)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="removeCate(scope.row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 5, 8, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCatedialogVisible"
      width="50%"
      @close="addCateClosed"
    >
      <!-- 添加分类表单 -->
      <el-form
        :model="addCateForm"
        :rules="addCaterules"
        ref="addCaterulesRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <!-- options数据源 -->
          <!-- props配置对象 -->

          <el-cascader
            v-model="selectedKeys"
            :options="ParentCateLest"
            :props="cascaderProps"
            @change="handleChange"
            clearable
            change-on-select
          ></el-cascader>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addCatedialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      title="修改分类"
      :visible.sync="editdialogVisible"
      width="50%"
      @close="editruleFormClose"
    >
      <el-form
        :model="editruleForm"
        :rules="editrules"
        label-width="100px"
        ref="editruleFormRef"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editruleForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addeditdialogVisible"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 编辑
      editdialogVisible: false,
      editruleForm: [],
      editrules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      // 父级分类数据列表
      ParentCateLest: [],
      selectedKeys: [],
      // 配置对象
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 表单验证
      addCaterules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      // 分类表单对象
      addCateForm: {
        // 分类父 ID
        cat_pid: 0,
        cat_name: '',
        // 分类层级
        cat_level: 0
      },
      // 控制添加分类
      addCatedialogVisible: false,
      //查询条件
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 商品分类的数据列表，默认为空
      catelist: [],
      //数据总条数
      total: 0,
      //   为table指定列数据
      columns: [
        {
          //标题
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          // 表示单前定义为模板列
          type: 'template',
          // 表示这一列的模板名称
          template: 'isok'
        },
        {
          label: '排序',
          // 表示单前定义为模板列
          type: 'template',
          // 表示这一列的模板名称
          template: 'order'
        },
        {
          label: '操作',
          // 表示单前定义为模板列
          type: 'template',
          // 表示这一列的模板名称
          template: 'opt'
        }
      ]
    }
  },
  created() {
    this.getcatelist()
  },
  methods: {
    // 获取数据分类
    async getcatelist() {
      const { data: res } = await this.$axios.get('categories', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.$message.error('数据获取失败')
      //   数据列表
      this.catelist = res.data.result
      //   总条数
      this.total = res.data.total
      //   console.log(res)
    },
    // 监听pagesize  展示几条数据
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getcatelist()
    },
    // 监听pagenum 第几页
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getcatelist()
    },
    // 打开控制分类
    showaddCate() {
      // 获取父级数据
      this.getParentCateLest()
      this.addCatedialogVisible = true
    },
    // 获取父级分类数据列表

    async getParentCateLest() {
      const { data: res } = await this.$axios({
        method: 'get',
        url: 'categories',
        params: {
          type: 2
        }
      })
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.ParentCateLest = res.data
      console.log(this.ParentCateLest)
    },
    // 选择项改变触发
    handleChange() {
      // console.log(this.selectedKeys)
      if (this.selectedKeys.length > 0) {
        //父类分类id
        this.addCateForm.cat_pid = this.selectedKeys[
          this.selectedKeys.length - 1
        ]
        // 为单前分类的等级赋值
        this.addCateForm.cat_level = this.selectedKeys.length
        return
      } else {
        this.addCateForm.cat_pid = 0
        this.addCateForm.cat_level = 0
      }
    },
    // 添加新分类
    addCate() {
      this.$refs.addCaterulesRef.validate(async val => {
        if (!val) return
        const { data: res } = await this.$axios.post(
          'categories',
          this.addCateForm
        )
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.$message.success('添加成功')
        this.getcatelist()
        this.addCatedialogVisible = false
      })
    },
    // 监听对话框关闭
    addCateClosed() {
      this.$refs.addCaterulesRef.resetFields()
      this.selectedKeys = []
      this.addCateForm.cat_pid = 0
      this.addCateForm.cat_level = 0
    },
    // 点击编辑获取数据

    async edit(id) {
      // 打开编辑宽

      // 根据id查询分类
      const { data: res } = await this.$axios.get('categories/' + id)
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.editruleForm = res.data
      console.log(this.editruleForm)
      this.editdialogVisible = true
    },
    // 关闭模态框
    editruleFormClose() {
      this.$refs.editruleFormRef.resetFields()
    },
    // 点击编辑的确定
    addeditdialogVisible() {
      this.$refs.editruleFormRef.validate(async val => {
        if (!val) return
        const { data: res } = await this.$axios.put(
          'categories/' + this.editruleForm.cat_id,
          { cat_name: this.editruleForm.cat_name }
        )
        if (res.meta.status !== 200) return this.$message.error('更新失败')
        this.$message.success('更新成功')
        this.getcatelist()
        this.editdialogVisible = false
      })
    },
    // 点击删除
    async removeCate(id) {
      console.log(id)
      const removeconfirm = await this.$confirm(
        '此操作将永久删除该商品, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // console.log(removeconfirm)
      if (removeconfirm === 'cancel') return this.$message.info('已取消删除')
      const { data: res } = await this.$axios.delete('categories/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      this.getcatelist()
    }
  }
}
</script>

<style lang="less" scoped>
.table {
  margin-top: 15px;
}
.el-cascader {
  width: 100%;
}
</style>
